“Visualizing your data should be the beginning and end of every project.”
“Think–what is the story you’re trying to tell? This picture should be worth a thousand words.”
There are two major sets of tools for creating plots in R:
Note that other plotting facilities do exist (notably lattice), but base and ggplot2 are by far the most popular.
## [1] "C:/Users/Julia/OneDrive/Documents/Berkeley/2020-01_Spring/PS239T_Spring2020/09_r-analysis-visualization/01_analysis"
## The following packages have been unloaded:
## pacman
For the following examples, we will using the gapminder dataset we saw last week. Gapminder is a country-year dataset with information on life expectancy, among other things.
The general call for ggplot2 looks like this:
The grammar involves some basic components:
The key to understanding ggplot2 is thinking about a figure in layers: just like you might do in an image editing program like Photoshop, Illustrator, or Inkscape. Each layer gets added on top of the previous one, so you can “stack” additional layers of information as needed.
Let’s look at an example:
So the first thing we do is call the ggplot function. This function lets R know that we’re creating a new plot, and any of the arguments we give the ggplot function are the global options for the plot: they apply to all layers on the plot.
Here, we’ve passed in two arguments to ggplot. First, we tell ggplot what data we want to show on our figure, in this example the gapminder data we read in earlier.
For the second argument we passed in the aes function, which tells ggplot how variables in the data map to aesthetic properties of the figure, in this case the x and y locations. Here we told ggplot we want to plot the lifeExp column of the gapminder data frame on the x-axis, and the gdpPercap column on the y-axis. Notice that we didn’t need to explicitly pass aes these columns (e.g. x = gapminder[, "lifeExp""]), this is because ggplot is smart enough to know to look in the data for that column!
By itself, the call to ggplot isn’t enough to draw a figure:
We need to tell ggplot how we want to visually represent the data, which we do by adding a new geom layer. In our example, we used geom_point, which tells ggplot we want to visually represent the relationship between x and y as a scatterplot of points:
Modify the example so that the figure visualise how life expectancy has changed over time:
Hint: the gapminder dataset has a column called “year”", which should appear on the x-axis.
aesIn the previous examples and challenge we’ve used the aes function to tell the scatterplot geom about the x and y locations of each point. Another aesthetic property we can modify is the point color.
In base plotting, we have to specify particular properties, like color="red" or size=10, which is a bit limiting if we have to do every modification by hand! Inside ggplot’s aes() function, however, these arguments are passed entire variables, whose values will then be displayed using different realizations of that aesthetic.
Color isn’t the only aesthetic argument we can set to display variation in the data. We can also vary by shape, size, etc. Try playing around with the options in the cell below.
In the previous challenge, you plotted lifExp over time. Using a scatterplot probably isn’t the best for visualising change over time. Instead, let’s tell ggplot to visualise the data as a line plot:
Instead of adding a geom_point layer, we’ve added a geom_line layer. We’ve added the by aesthetic, which tells ggplot to draw a line for each country.
But what if we want to visualise both lines and points on the plot? We can simply add another layer to the plot:
ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line() +
geom_point()It’s important to note that each layer is drawn on top of the previous layer. In this example, the points have been drawn on top of the lines. Here’s a demonstration:
ggplot(data = dat, aes(x=year, y=lifeExp, by=country)) +
geom_line(aes(color=continent)) +
geom_point()In this example, the aesthetic mapping of color has been moved from the global plot options in ggplot to the geom_line layer so it no longer applies to the points. Now we can clearly see that the points are drawn on top of the lines.
Switch the order of the point and line layers from the previous example. What happened?
Labels are considered to be their own layers in ggplot.
# add x and y axis labels
ggplot(data = dat, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point() +
xlab("GDP per capita") +
ylab("Life Expectancy") +
ggtitle("My fancy graph")So are scales:
# limit x axis from 1,000 to 20,000
ggplot(data = dat, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point() +
xlab("GDP per capita") +
ylab("Life Expectancy") +
ggtitle("My fancy graph") +
xlim(1000, 20000)## Warning: Removed 515 rows containing missing values (geom_point).
Note that we get a warning message that some of the data has been dropped due to the new limits we imposed.
ggplot also makes it easy to overlay statistical models over the data. To demonstrate we’ll go back to an earlier example:
We can change the scale of units on the x axis using the scale functions. These control the mapping between the data values and visual values of an aesthetic. This is nice because we don’t have to apply the transformations we might want for graphing on our real data:
ggplot(data = dat, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point() +
scale_x_log10()The log10 function applied a transformation to the values of the gdpPercap column before rendering them on the plot, so that each multiple of 10 now only corresponds to an increase in 1 on the transformed scale, e.g. a GDP per capita of 1,000 is now 3 on the y axis, a value of 10,000 corresponds to 4 on the x axis and so on. This makes it easier to visualise the spread of data on the x-axis.
We can fit a simple relationship to the data by adding another layer, stat_smooth (in many cases, but not all, geom_smooth and stat_smooth are interchangeable):
ggplot(data = dat, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point() +
scale_x_log10() +
stat_smooth(method="lm")## `geom_smooth()` using formula 'y ~ x'
Note that we currently have 5 lines, one for each region, because the color option is the global aes function.. But if we move it, we get different restuls:
ggplot(data = dat, aes(x = gdpPercap, y = lifeExp)) +
geom_point(aes(color=continent)) +
scale_x_log10() +
stat_smooth(method="lm")## `geom_smooth()` using formula 'y ~ x'
Now the stat_smooth operation is only acting on the x and y specified within aes. This tells us that what we specify as our aesthetic also affects future layers. Here, the color aesthetic is only applied to the mapping of geom_point, not the line generated by stat_smooth.
As you might expect, we can set other properties within each additional layer as well. Here, we can make the line thicker by setting the size aesthetic in the geom_smooth layer:
ggplot(data = dat, aes(x = gdpPercap, y = lifeExp)) +
geom_point(aes(color=continent)) +
scale_x_log10() +
stat_smooth(method="lm", size = 1.5)## `geom_smooth()` using formula 'y ~ x'
Modify the color and size of the points on the point layer in the previous example so that they are fixed (i.e. not reflective of continent).
Hint: do not use the first aes function.
Earlier we visualised the change in life expectancy over time across all countries in one plot. Alternatively, we can split this out over multiple panels by adding a layer of facet panels:
dat %>%
mutate(continent=factor(continent,
levels=c("Africa", "Oceania", "Americas", "Asia", "Europe"))) %>%
ggplot(aes(x = year, y = lifeExp, color=country)) +
geom_line() +
facet_wrap( ~ continent) +
theme(legend.position="none") # Let's start with this plot
ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line() +
geom_point()# Make points transparent
ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7)# Change color scale
ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_colour_manual(values = c("red", "blue", "green", "black", "yellow"))# Change color scale using hex codes using codes from http://colorbrewer2.org/#type=qualitative&scheme=Dark2&n=5
ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_colour_manual(values = c("#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e"))# Change color scale using colorbrewer
ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_color_brewer(palette="Dark2")# Change color scale using viridis
ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_colour_viridis_d(option="A")ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_colour_viridis_d(option="D")Themes control multiple elements of the chart formatting at once. See the following examples.
ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_colour_viridis_d(option="A") +
theme_bw()ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_colour_viridis_d(option="A") +
theme_economist()ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_colour_viridis_d(option="A") +
theme_stata()ggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_colour_viridis_d(option="A") +
theme_edggplot(data = dat, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line(alpha=.4) +
geom_point(alpha=.7) +
scale_colour_viridis_d(option="A") +
theme_ed_bigtxtThis is just a taste of what you can do with ggplot2. RStudio provides a really useful cheat sheet of the different layers available, as do the authors of the R Graphic cookbook, and more extensive documentation is available on the ggplot2 website. Finally, if you have no idea how to change something, a quick google search will usually send you to a relevant question and answer on Stack Overflow with reusable code to modify!
bar plots
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
# with color representing regions
ggplot(data = dat, aes(x = lifeExp, fill = continent)) + geom_bar(stat="bin")## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
box plots
Create a density plot of GDP per capita, filled by continent.
Advanced: - Transform the x axis to better visualise the data spread. - Add a facet layer to panel the density plots by year.
Exporting with ggplot
Basic syntax:
# Assume we saved our plot is an object called example.plot
ggsave(filename="../Plots/example-ggplot.pdf",
plot=example.plot, scale=, width=, height=)Example:
ggplot(data = dat, aes(x = gdpPercap, y = lifeExp)) +
geom_point(color="grey50", alpha=.5) +
scale_x_log10() +
stat_smooth(method="lm", size = 1.5, alpha=.75) +
scale_colour_viridis_d(option="D") +
theme_ed## `geom_smooth()` using formula 'y ~ x'
## Saving 12 x 8 in image
## `geom_smooth()` using formula 'y ~ x'